package com.kk.controller;

import com.kk.common.Result;
import com.kk.dao.ContentDao;
import com.kk.model.Content;
import com.kk.model.Nav;
import com.kk.util.ToolUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/content")
public class ContentController {

    private static final String PREFIX = "system/content/";

    @Autowired
    private ContentDao contentDao;

    @GetMapping("")
    public String index(Model model) {
        List<Content> contentList = contentDao.findAll();
        if (contentList.size() > 0) {
            model.addAttribute("content", contentList.get(0));
        }
        return PREFIX + "content";
    }

    @CrossOrigin(maxAge = 3600)
    @GetMapping("/content")
    @ResponseBody
    public Result content() {
        List<Content> contentList = contentDao.findAll();
        if (contentList.size() > 0) {
            Content content = contentList.get(0);
            List<Nav> navList = content.getNavList();
            Collections.sort(navList, (o1, o2) -> o1.getSort() < o2.getSort() ? -1 : 1);
            content.setNavList(navList);
            return Result.success(content);
        }
        return Result.error("400", "未查询到相关数据");
    }

    @PostMapping("/edit")
    @ResponseBody
    public Result edit(@RequestBody Content content) {
        if (ToolUtils.isNotEmpty(content)) {
            Content content1 = contentDao.save(content);
            return Result.success(content1);
        }
        return Result.error("400", "请求参数为空");
    }


}
